<template>
  <div class="courseDetail-detail-view-page">
    <div v-if="courseDetail" style="padding: 30px">
      <!-- <div>课程详情</div>
      <div>{{ courseDetail.title }}</div>
      <div>{{ courseDetail.desc }}</div>
      <div>{{ courseDetail.teachername }}</div>
      <div v-html="courseDetail.coursedetail"></div>
      <div>{{ courseDetail.description }}</div>
      <div>{{ courseDetail.courseduration }}</div>
      <div>{{ courseDetail.coursepitchnumber }}</div>
-->
      <div class="courseDetail-details">
        <h1>{{ courseDetail.title }}</h1>

        <section class="basic-info">
          <p><strong>上课老师：</strong>{{ courseDetail.teachername }}</p>
          <p><strong>课程科目：</strong>{{ courseDetail.title }}</p>
          <p><strong>科目描述：</strong>{{ courseDetail.description }}</p>
          <p><strong>上课时长：</strong>{{ courseDetail.courseduration }}</p>
          <p><strong>上课节数：</strong>{{ courseDetail.coursepitchnumber }}</p>
        </section>

        <section class="courseDetail-description" v-if="isLearn">
          <h2>课程详情</h2>
          <div v-html="courseDetail.coursedetail"></div>
        </section>

        <section class="courseDetail-video" v-if="isLearn">
          <h2>课程视频</h2>
          <video
            ref="videoPlayer"
            :src="videoUrl"
            controls
            @timeupdate="updatePlaybackTime"
            @ended="savePlaybackTime"
            @play="startSaving"
            @pause="stopSaving"
          ></video>
          <p>当前播放时长：{{ playbackTime }} 秒</p>
        </section>
      </div>

      <div style="width: 100%; text-align: center" v-if="!isLearn">
        <a-button type="primary" v-if="isShowSubmitButton" @click="handleOk" style="width: 300px" size="large">选择课程</a-button>
        <a-button type="primary" v-else @click="handleCallback">返回</a-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { computed, onMounted, onUnmounted, ref } from 'vue';
  import { getToken } from '/@/utils/auth';
  import { router } from '/@/router';
  import { getMyCourseList, saveOrUpdate } from '../myCourseManagement/MyCourseManagement.api';
  import { queryCourseManagementById } from '../courseManagement/CourseManagement.api';
  import { PageEnum } from '/@/enums/pageEnum';
  import { message } from 'ant-design-vue';
  import { useRoute } from 'vue-router';

  import videoUrl from '@/assets/video/video.mp4';
  import { getUserInfo } from '/@/api/sys/user';
  import { saveOrUpdateUser } from '../system/user/user.api';

  const courseDetail = ref();
  const myCourseList = ref([]);

  const playbackTime = ref(0);
  const videoPlayer = ref<HTMLVideoElement | null>(null);

  const userInfo = ref();
  let saveInterval: NodeJS.Timeout | null = null;
  let isPlaying = false;
  const isLearn = ref(false);

  const route = useRoute();

  const isShowSubmitButton = computed(() => {
    if (!courseDetail.value || !courseDetail.value.id) {
      return false;
    }
    return myCourseList.value.findIndex((child) => child.courseId == courseDetail.value.id) == -1;
  });

  const updatePlaybackTime = () => {
    if (videoPlayer.value) {
      playbackTime.value = Math.floor(videoPlayer.value.currentTime);
    }
  };

  // 开始保存
  const startSaving = () => {
    if (!isPlaying) {
      isPlaying = true;
      saveInterval = setInterval(savePlaybackTime, 3000);
    }
  };

  // 停止保存
  const stopSaving = () => {
    isPlaying = false;
    if (saveInterval) {
      clearInterval(saveInterval);
      saveInterval = null;
    }
  };

  // 保存播放时长到数据库
  const savePlaybackTime = async () => {
    if (!isLearn.value) {
      return;
    }
    try {
      await saveOrUpdateUser({ ...userInfo.value, videoPlaybackTime: playbackTime.value }, true);
      console.log('播放时长保存成功');
    } catch (error) {
      console.error('保存播放时长失败', error);
    }
  };

  const handleCallback = () => {
    router.replace({ path: PageEnum.INDEX_PAGE, query: { redirect: 'index' } });
  };

  const handleOk = async () => {
    if (!getToken()) {
      router.replace({ path: PageEnum.BASE_LOGIN, query: { redirect: 'index' } });
      return;
    }
    const index = myCourseList.value.findIndex((child) => child.courseId == courseDetail.value.id);
    if (index > -1) {
      return;
    }
    const params = {
      ...courseDetail.value,
      courseId: courseDetail.value.id,
    };
    const res = await saveOrUpdate(params, false);
    console.log('index 添加课程 res ==>', res);
    message.success('添加成功');
  };

  const loadMyCourseData = async () => {
    const params = {
      column: 'createTime',
      order: 'desc',
      pageNo: 1,
      pageSize: 100,
    };
    const res = await getMyCourseList(params);
    myCourseList.value = res.records || [];
  };

  const loadData = async () => {
    const id = route.query.id;
    const res = await queryCourseManagementById({ id: id });
    console.log('res ==>', res);
    courseDetail.value = res || {};
  };

  onUnmounted(() => {
    stopSaving();
    savePlaybackTime();
  });

  onMounted(() => {
    loadData();
    if (!getToken()) {
      return;
    }
    loadMyCourseData();
    if (route.query.isLearn == 'true') {
      isLearn.value = true;
      getUserInfo().then((res) => {
        console.log('getUserInfo  res ==>', res);
        userInfo.value = res?.userInfo;
        playbackTime.value = res?.userInfo.videoPlaybackTime;
      });
    }
  });
</script>

<style lang="less" scoped>
  .courseDetail-detail-view-page {
    width: 100%;
    height: 100%;

    display: flex;
    justify-content: center;
    align-items: flex-start;

    overflow-y: auto;

    .course-details {
      // max-width: 800px;
      max-width: 1000px;
      margin: 0 auto;
      font-family: Arial, sans-serif;
    }

    .basic-info p {
      margin: 8px 0;
    }

    .course-description {
      margin-top: 20px;
    }

    .course-video {
      margin-top: 20px;
    }

    video {
      width: 100%;
      max-height: 450px;
      margin-bottom: 10px;
    }
  }
</style>
